'''
fuction : 与服务器建立连接
author  : 辛天宇
date    : 2024-4-9
-------------------------------
author date  modify

'''
import socket
import global_var

def connect_to_server(): 
    # 设置服务器地址和端口  
    server_address = (global_var.SERVER_IP, global_var.SERVER_PORT) 
    # 创建一个socket对象  
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  
      
    # 尝试连接到服务器  
    try:  
        client_socket.connect(server_address)  
        print(f'Connected to {server_address}')  
        return client_socket  
    except Exception as e:  
        print(f'Failed to connect to server: {e}')  
        return None  
def disconnect_to_server(client_socket):
    # 关闭连接  
    print('Closing socket')  
    client_socket.close() 
  
def process_data(client_socket):  
    # 接收用户输入并发送给服务器  
    if global_var.FLAG == 1:
        global_var.FLAG=0
        try:  
            user_input = global_var.TX_BUF
            print(f"TX_BUF={user_input}")  
            if user_input.lower() == 'exit':  
                cmd = 'Q'  
                client_socket.sendall(cmd.encode())
                return 0
            client_socket.sendall(user_input.encode())  

            # 接收服务器的响应  
            data = client_socket.recv(512)  
            print(f'Received: {data.decode()}') 
            global_var.RX_BUF = data
            print(f'RX_BUF: {data.decode()}') 

        except KeyboardInterrupt:
            print('\nKeyboardInterrupt received, exiting...')  
            return -1
        except ConnectionResetError:  
            print('\nConnection reset by server, exiting...')  
            return  -2
        except Exception as e:  
            print(f'An error occurred: {e}, trying to reconnect...')  
            client_socket.close()  # 关闭当前socket
            return  -3
    return 0
         
  
def Client_server():  
    # 尝试连接到服务器  
    client_socket = connect_to_server()  
    if client_socket is not None:  
        while True:
            # 如果连接成功，则处理数据
            cmd = input(">>>>")
            global_var.FLAG=1
            global_var.TX_BUF = cmd
            process_data(client_socket) 

def main():
    Client_server()

if __name__ == '__main__':
    main()